package com.example.myapplication3

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.telephony.TelephonyManager
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun customToast(view: View) {
        val toast = Toast(this)
        toast.view = TextView(this).apply {
            text = "这是自定义消息"
            setTextColor(Color.WHITE)
            setBackgroundColor(Color.BLACK)
        }
        Handler().postDelayed({
            Toast.makeText(this, "这是系统样式消息", Toast.LENGTH_SHORT).show()
//            toast.show()
        }, 3000)
    }

    fun getAllApps(view: View) {
        try {
            val packageInfos =
                packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES or PackageManager.GET_SERVICES)
            for (info in packageInfos) {
                val pkg = info.packageName
                Log.d("lzh", info.packageName)
            }
        } catch (t: Throwable) {
            t.printStackTrace()
        }
    }

    fun getPhoneNumber(view: View) {
        val permission = Manifest.permission.READ_PHONE_STATE
        val permission2 = Manifest.permission.READ_PHONE_NUMBERS
        ActivityCompat.requestPermissions(this, arrayOf(permission, permission2), 100)
        val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        val phoneNumber = tm.line1Number
        Toast.makeText(this, phoneNumber, Toast.LENGTH_SHORT).show()
    }

    fun getPhoneNumber2(view: View) {
        val permission = Manifest.permission.READ_PHONE_STATE
        val permission2 = Manifest.permission.READ_PHONE_NUMBERS
        ActivityCompat.requestPermissions(this, arrayOf(permission, permission2), 100)
        val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_NUMBERS
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        val phoneNumber = tm.line1Number
        Toast.makeText(this, phoneNumber, Toast.LENGTH_SHORT).show()
    }

}